#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# to play subtitles properly add -subpos 90 -spualign 2 -spuaa 4 to mplayer

from dvd import dvd
import sys,re,urllib

class MainWindow:
        def __init__(self):
		self.dev = "/dev/dvd"
		self.dest = "/tmp/"
		self.aCodec = "ogg2"
		self.vCodec = "h264"
		self.title = 1
		self.audios = 0
		self.size = 1000
		self.dvd = dvd(self.dev)
		self.mkv = []

        def getTitleData(self):
		res = ""
		t = self.dvd.titles()
		for i in range(len(t)):
			if self.dvd.title(i + 1)['length'] > 1200:
				self.title = i + 1 
				if not self.dvd.scanned(self.title):
					self.dvd.parseTitle(self.title)
				datos = self.dvd.title(self.title)
				try:
                        	       	print  "\n#T:" + str(datos['title']) + " - " + str(seg2time(datos['length'])) + " hr"
                        	except :
                        	       	print  "\n#T:" + str(datos['title']) 
				print "\techo \"RIPEAMOS Titulo [" + str(self.title) + "] del DVD --> a 1000MB\""
				print "\tmplayer dvd://"+str(self.title)+" -dvd-device \"" + self.dev + "\" -dumpstream -dumpfile \"" + str(self.dest)+ "dvd-T"+str(self.title)+".vob\""
				print "dvdxchap -t " + str(self.title) + " \"" + self.dev + "\" > \"" + str(self.dest)+"chapter-T"+str(self.title)+".txt\""

				for j in datos['audio']:
					id 	= str(j['id']) 
					aid 	= str(j['aid']) 
					lang 	= str(j['lang'])
					codec 	= str(j['formato'])
					fid 	= "audio-t"+str(self.title)+"-"+str(j['id'])+"-"+lang
					lang3 	= expLang(lang)
					print  " # AUDIO: " + id + "-" + lang + "-" + codec + "(" + str(j['canales']) + ") #"
					print  "\techo  \"AUDIO [" + id + "] IDIOMA " + lang + " CODEC " + codec + " --> " + self.aCodec + "\"" 

					if self.aCodec == "ac3":
						print "\tmencoder -nocache -mc 0 -aid " + str(aid) + " -o \"" + str(self.dest) + fid + ".ac3\" -ovc copy -of rawaudio -oac copy \"" + str(self.dest)+ "dvd-T"+str(self.title)+".vob\"" 
						print "\tmkvmerge -o \"" + str(self.dest) + fid + ".mka\" --language 0:"+ lang3 + " \"" + str(self.dest) +  fid + ".ac3\""
						self.mkv += ["\"" + str(self.dest) + fid + ".mka\""]

					elif self.aCodec == "ogg2":
						print "\tmkfifo \"" + str(self.dest)+ "fifo-" + fid + "\""
						print "\toggenc -r -R 44100 -q 3 -C 2 -o \"" + str(self.dest) + fid + ".ogg\" \"" + str(self.dest)+ "fifo-" + fid + "\"&",
						print "\tmplayer -nolirc -nocache -noframedrop -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.dest)+ "fifo-" + fid + "\" -srate 44100 -af volnorm=1 -aid " + str(aid) + " \"" + str(self.dest)+ "dvd-T"+str(self.title)+".vob\""
						print "\trm \"" + str(self.dest)+ "fifo-" + fid + "\""
						print "\tmkvmerge -o \"" + str(self.dest) + fid + ".mka\" --language 0:"+ lang3 + " \"" + str(self.dest) + fid + ".ogg\""
						self.mkv += ["\"" + str(self.dest) + fid + ".mka\""]

					elif self.aCodec == "ogg6":
						print "\tmkfifo \"" + str(self.dest)+ "fifo-" + fid + "\""
						print "\toggenc -r -R 44100 -q 3 -C 6 -o \"" + str(self.dest) + fid + ".ogg\" \"" + str(self.dest)+ "fifo-" + fid + "\"&",
						print "\tmplayer -nolirc -nocache -noframedrop -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.dest)+ "fifo-" + fid + "\" -srate 44100 -af volnorm=1,lavcresample=44100 -channels 6 -aid " + str(aid) + " \"" + str(self.dest)+ "dvd-T"+str(self.title)+".vob\""
						print "\trm \"" + str(self.dest)+ "fifo-" + fid + "\""
						print "\tmkvmerge -o \"" + str(self.dest) + fid + ".mka\" --language 0:"+ lang3 + " \"" + str(self.dest) + fid + ".ogg\""
						self.mkv += ["\"" + str(self.dest) + fid + ".mka\""]

					elif self.aCodec == "mp3":
						print "\tmkfifo \"" + str(self.dest)+ "fifo-" + fid + "\""
						print "\tlame --nohist -h -r -x --preset fast standard \"" + str(self.dest)+ "fifo-" + fid + "\"  \"" + str(self.dest) + fid + ".mp3\" &",
						print "\tmplayer -nolirc -nocache -noframedrop -mc 0 -vc null -vo null -ao pcm:nowaveheader:file=\"" + str(self.dest)+ "fifo-" + fid + "\" -af volnorm=1 -aid " + str(aid) + " \"" + str(self.dest)+ "dvd-T"+str(self.title)+".vob\""
						print "\trm \"" + str(self.dest)+ "fifo-" + fid + "\""
						print "\tmkvmerge -o \"" + str(self.dest) + fid + ".mka\" --language 0:"+ lang3 + " \"" + str(self.dest) + fid + ".mp3\""
						self.mkv += ["\"" + str(self.dest) + fid + ".mka\""]
							
				print  " #SUBS # "
				for sub in datos['sub']:
					id 	= str(sub['id']) 
					lang 	= str(sub['lang'])
					fid 	= "sub-t"+str(self.title)+"-"+str(sub['id'])+"-"+str(sub['lang'])
					lang3 	= expLang(str(sub['lang']))

					print "\techo \"SUBTITULOS [" + id + "] IDIOMA " + lang + "\""
					print "\tmencoder dvd://"+str(self.title)+" -dvd-device \"" + self.dev + "\" -nocache -nosound -of rawaudio -ovc copy -o /dev/null -vobsubout \"" + str(self.dest) + fid + "\" -vobsuboutindex 0 -vobsuboutid " + lang + " -sid " + id 
					#text += "\necho \"custom colors: ON, tridx: 1000, colors: 000000, 000000, ffffff, 000000\" >> \"" + str(self.dest) + fid + ".idx\""
					self.mkv += ["\"" + str(self.dest) + fid + ".idx\""] 

				print " # VIDEO #"
				cropCmd = self.cropping()
				bitRate = 1000
				filtros = "pullup,softskip" + cropCmd + ",harddup,scale"
				if self.vCodec == 'h264' :
					# mas rápido
					opsPasada1 = "bitrate=" + str(bitRate) + ":subq=2:frameref=3:me=umh:partitions=all:bframes=3:b_pyramid:weight_b:cabac=1:8x8dct:turbo=1:pass=1:threads=auto"
					opsPasada2 = "bitrate=" + str(bitRate) + ":subq=6:frameref=3:me=umh:partitions=all:bframes=3:b_pyramid:weight_b:cabac=1:8x8dct:pass=2:threads=auto"
					# mas lento
					# opsPasada1 = "bitrate=" + str(bitRate) + ":pass=1:crf=19:turbo=1:me=umh:me_range=19:nodct_decimate:nointerlaced:8x8dct:threads=auto:nofast_pskip:nobrdo:trellis=1:partitions=p8x8,b8x8,i8x8,i4x4:mixed_refs:bime:frameref=3:bframes=4:b_adapt:b_pyramid:weight_b:direct_pred=auto:subq=5:chroma_me:cabac:deblock"
					# opsPasada2 = "bitrate=" + str(bitRate) + ":pass=2:me=umh:me_range=19:nodct_decimate:nointerlaced:8x8dct:threads=auto:nofast_pskip:nobrdo:trellis=1:partitions=p8x8,b8x8,i8x8,i4x4:mixed_refs:bime:frameref=3:bframes=4:b_adapt:b_pyramid:weight_b:direct_pred=auto:subq=5:chroma_me:ssim:cabac:deblock"
					print "\tmencoder \"" + str(self.dest) + "dvd-T"+str(self.title)+".vob\" -zoom -xy 640 -vf " + filtros + " -oac copy -sws 10 -ovc x264 -x264encopts " + opsPasada1 + " -of rawvideo -o /dev/null 2> /dev/null"
					print "\techo \"SEGUNDA PASADA\""
					print "\tmencoder \"" + str(self.dest) + "dvd-T"+str(self.title)+".vob\" -zoom -xy 640 -vf " + filtros + " -oac copy -sws 10 -ovc x264 -x264encopts " + opsPasada2 + " -of rawvideo -o \"" + str(self.dest) + "video-t"+str(self.title)+".264\" 2> /dev/null"
					print "\tmp4creator -c \"" + str(self.dest) + "video-t"+str(self.title)+".264\" -rate 25 \"" + str(self.dest) + "video-t"+str(self.title)+".mp4\""
					self.mkv += ["\"" + str(self.dest) + "video-t"+str(self.title)+".mp4\""] 
	
				elif self.vCodec == 'xvid' :
					print "\tmencoder \"" + str(self.dest) + "dvd-T"+str(self.title)+".vob\" -vf " + filtros + " -zoom -xy 640  -ovc xvid -xvidencopts bitrate=" + str(bitRate) + ":pass=1:chroma_opt:vhq=4:bvhq=1:quant_type=mpeg -oac copy  -o /dev/null 2> /dev/null"
					print "\tmencoder \"" + str(self.dest) + "dvd-T"+str(self.title)+".vob\" -vf " + filtros + " -zoom -xy 640  -ovc xvid -xvidencopts bitrate=" + str(bitRate) + ":pass=2:chroma_opt:vhq=4:bvhq=1:quant_type=mpeg -oac copy  -o \"" + str(self.dest) + "video-t"+str(self.title)+".xvid\" 2> /dev/null"
					self.mkv += ["\"" + str(self.dest) + "video-t"+str(self.title)+".xvid\""] 
				
				print " # MKV #"
				print "\techo \"Juntamos el Titulo [" + str(self.title) + "] en un MKV\""
				text = "\tmkvmerge -o \"" + str(self.dest)+ "final-dvd-T" + str(self.title) + ".mkv\""
				for i in self.mkv:
					if "idx" in i:
						text += " --delay 0:0ms " + str(i) 
					else:
						text += " --delay 1:0ms " + str(i) 
				text += " --chapter-language spa  --chapters \"" + str(self.dest)+"chapter-T"+str(self.title)+".txt\""
				print text
	
	def volcado (self):
		return text

#	def chapters (self):
#		return ""
#
	def cropping (self, cmd = ""):
		import re, sys
		# CROP
		if not cmd:
			cmd = str("mplayer dvd://" + str(self.title) + " -dvd-device \"" + self.dev + "\" -nosound -vo null -vf cropdetect -sstep 170 -frames 30")
		cropData = commands.getoutput(cmd)
		crops = []
		for i in cropData.split("\n"):
			try:
				crops.append(re.search("(\d+:\d+:\d+:\d+)\)", i).groups()[0])
			except AttributeError:
				pass	
		maxCount = 0
		cropCmd = ""
		for i in crops:
			if crops.count(i) > maxCount:
				maxCount = crops.count(i)
				cropCmd = i
		if cropCmd == "":
			crops = []
			for ss in [200,400,600,800]:
				cmd = str("mplayer dvd://" + str(self.title) + " -dvd-device \"" + self.dev + "\" -nosound -vo null -vf cropdetect -ss " + str(ss) +" -frames 5")
				cropData = commands.getoutput(cmd)
				for i in cropData.split("\n"):
					try:
						crops.append(re.search("(\d+:\d+:\d+:\d+)\)", i).groups()[0])
					except AttributeError:
						pass	
			maxCount = 0
			cropCmd = ""
			for i in crops:
				if crops.count(i) > maxCount:
					maxCount = crops.count(i)
					cropCmd = i
			if cropCmd == "":
				print "\n\n #NO SE HA ENCONTRADO CROPPING"
				sys.exit(-1)
		return ",crop=" + cropCmd
def expLang (lang):
	data = {'None':'non','unknown':'non', 'ab':'abk', 'aa':'aar', 'af':'afr', 'ak':'aka', 'sq':'alb', 'am':'amh', 'ar':'ara', 'an':'arg', 'hy':'arm', 'as':'asm', 'av':'ava', 'ae':'ave', 'ay':'aym', 'az':'aze', 'bm':'bam', 'ba':'bak', 'eu':'baq', 'be':'bel', 'bn':'ben', 'bh':'bih', 'bi':'bis', 'nb':'nob', 'bs':'bos', 'br':'bre', 'bg':'bul', 'my':'bur', 'es':'spa', 'ca':'cat', 'ch':'cha', 'ce':'che', 'ny':'nya', 'ny':'nya', 'zh':'chi', 'za':'zha', 'cu':'chu', 'cu':'chu', 'cu':'chu', 'cu':'chu', 'cu':'chu', 'cv':'chv', 'kw':'cor', 'co':'cos', 'cr':'cre', 'hr':'scr', 'cs':'cze', 'da':'dan', 'dv':'div', 'nl':'dut', 'dz':'dzo', 'en':'eng', 'eo':'epo', 'et':'est', 'ee':'ewe', 'fo':'fao', 'fj':'fij', 'fi':'fin', 'fr':'fre', 'fy':'fry', 'ff':'ful', 'gd':'gla', 'gl':'glg', 'lg':'lug', 'ka':'geo', 'de':'ger', 'ki':'kik', 'el':'gre', 'kl':'kal', 'gn':'grn', 'gu':'guj', 'ha':'hau', 'he':'heb', 'iw':'heb', 'hz':'her', 'hi':'hin', 'ho':'hmo', 'hu':'hun', 'is':'ice', 'io':'ido', 'ig':'ibo', 'id':'ind', 'ia':'ina', 'ie':'ile', 'iu':'iku', 'ik':'ipk', 'ga':'gle', 'it':'ita', 'ja':'jpn', 'jv':'jav', 'kl':'kal', 'kn':'kan', 'kr':'kau', 'ks':'kas', 'kk':'kaz', 'km':'khm', 'ki':'kik', 'rw':'kin', 'ky':'kir', 'kv':'kom', 'kg':'kon', 'ko':'kor', 'kj':'kua', 'ku':'kur', 'kj':'kua', 'lo':'lao', 'la':'lat', 'lv':'lav', 'lb':'ltz', 'li':'lim', 'li':'lim', 'li':'lim', 'ln':'lin', 'lt':'lit', 'lu':'lub', 'lb':'ltz', 'mk':'mac', 'mg':'mlg', 'ms':'may', 'ml':'mal', 'mt':'mlt', 'gv':'glv', 'mi':'mao', 'mr':'mar', 'mh':'mah', 'mo':'mol', 'mn':'mon', 'na':'nau', 'nv':'nav', 'nv':'nav', 'nd':'nde', 'nr':'nbl', 'ng':'ndo', 'ne':'nep', 'se':'sme', 'nd':'nde', 'no':'nor', 'nb':'nob', 'nn':'nno', 'ny':'nya', 'nn':'nno', 'oc':'oci', 'oj':'oji', 'cu':'chu', 'or':'ori', 'om':'orm', 'os':'oss', 'os':'oss', 'pi':'pli', 'pa':'pan', 'fa':'per', 'pl':'pol', 'pt':'por', 'oc':'oci', 'ps':'pus', 'qu':'que', 'rm':'roh', 'ro':'rum', 'rn':'run', 'ru':'rus', 'sm':'smo', 'sg':'sag', 'sa':'san', 'sc':'srd', 'gd':'gla', 'sr':'scc', 'sn':'sna', 'ii':'iii', 'sd':'snd', 'si':'sin', 'sk':'slo', 'sl':'slv', 'so':'som', 'st':'sot', 'nr':'nbl', 'es':'spa', 'su':'sun', 'sw':'swa', 'ss':'ssw', 'sv':'swe', 'tl':'tgl', 'ty':'tah', 'tg':'tgk', 'ta':'tam', 'tt':'tat', 'te':'tel', 'th':'tha', 'bo':'tib', 'ti':'tir', 'to':'ton', 'ts':'tso', 'tn':'tsn', 'tr':'tur', 'tk':'tuk', 'tw':'twi', 'ug':'uig', 'uk':'ukr', 'ur':'urd', 'uz':'uzb', 've':'ven', 'vi':'vie', 'vo':'vol', 'wa':'wln', 'cy':'wel', 'wo':'wol', 'xh':'xho', 'yi':'yid', 'yo':'yor', 'za':'zha', 'zu':'zul' }
	if data.has_key(str(lang)):
		return data[lang]
def seg2time(seg):
	hor = str (int(seg/60/60))
	min = str (int(seg/60)-int(hor)*60)
	seg = str(int(seg-int(seg/60)*60))		
	return hor + ":" + min + ":" + seg

def help():
	print 'Usage: dvd2mkv [option]'
	print 'options:'
	print '-h : shows this help'
	print '-t X : where X = title number'
	print '-m X : where X = limit of MB for the film'


if __name__ == "__main__":
	# programas requeridos:
	#	transcode
	#	mplayer
	#	mencoder
	#	mpeg4ip		-> mp4creator
	#	mkvtoolnix	-> mkvmerge
	#	subtitleripper 	-> subtitle2vobsub
	import getopt, commands
	from sys import argv
	from sys import exit
	for i in ['apt-get', 'emerge'] :
		cmd = "which "+i
		cmdOut = commands.getoutput(cmd)
		if i not in cmdOut:
			pass
		else:
			instApp = i

	for i in [['mplayer','mplayer'], ['mencoder','mencoder'], ['subtitle2vobsub','subtitleripper'], ['mkvmerge','mkvtoolnix'], ['mp4creator','mpeg4ip'],['dvdxchap','ogmtools']] :
		cmd = "which "+i[0]
		cmdOut = commands.getoutput(cmd)
		if i[0] not in cmdOut:
			print "## Debes instalar: ", i[0], " Instalalo con : sudo", instApp , i[1]
        		sys.exit()
	param = sys.argv
	ripea = 0
	audios = 0
	dvd = MainWindow()
	dvd.titles = dvd.dvd.titles()
	dvd.getTitleData()	
